package com.mygame.game_server.cmdHandle;

import com.mygame.game_server.User;
import com.mygame.game_server.caster.Broadcaster;
import com.mygame.game_server.manager.UserManager;
import com.mygame.game_server.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

/**
 * @author Jim
 * @date 23:04 2022/5/6
 * @description
 * @email:huwmz04153277@126.com
 */
public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd>{

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {

        if (null == ctx || null == cmd) {
            return;
        }

        /**
         * 用户移动
         */
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if (null == userId) {
            return;
        }
        //获取已登录用户
        User existUser = UserManager.getUserById(userId);

        if (null == existUser) {
            return;
        }

        long nowTime = System.currentTimeMillis();
        existUser.moveState.fromPosX = cmd.getMoveFromPosX();
        existUser.moveState.fromPosY = cmd.getMoveFromPosX();
        existUser.moveState.toPosY = cmd.getMoveToPosY();
        existUser.moveState.toPosX = cmd.getMoveToPosX();
        existUser.moveState.startTime = nowTime;



        GameMsgProtocol.UserMoveToResult.Builder resultBuilder = GameMsgProtocol.UserMoveToResult.newBuilder();
        resultBuilder.setMoveUserId(userId);
        resultBuilder.setMoveFromPosX(cmd.getMoveFromPosX());
        resultBuilder.setMoveFromPosY(cmd.getMoveFromPosY());
        resultBuilder.setMoveToPosY(cmd.getMoveToPosY());
        resultBuilder.setMoveToPosX(cmd.getMoveToPosX());
        resultBuilder.setMoveStartTime(System.currentTimeMillis());

        GameMsgProtocol.UserMoveToResult newResult = resultBuilder.build();
        Broadcaster.broadcaster(newResult);
    }
}
